import redis
import json
import os
import uuid
from flask import Flask, request, jsonify, render_template, redirect, url_for, session, send_from_directory
import time
# 配置文件上传目录
UPLOAD_FOLDER = './uploads'  # 图片保存目录
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
time_flag = 1
app = Flask(__name__)
app.secret_key = 'haoxue1234@haoxue'


# 配置 Redis
redis_pool = redis.ConnectionPool(host='116.62.120.28', port=6379, db=0, password="qp123456", decode_responses=True)
redis_client = redis.StrictRedis(connection_pool=redis_pool)


@app.before_request
def auth():
    print(session)
    now = time.localtime().tm_mday
    global time_flag
    if now != time_flag:
        time_flag = now
        for filename in os.listdir(UPLOAD_FOLDER):
            file_path = os.path.join(UPLOAD_FOLDER, filename)
            os.remove(file_path)
    if 'username' not in session:
        if request.path != "/login":
            return render_template('login.html')
    else:
        if request.path == "/":
            return render_template('index.html')


@app.route('/login', methods=['POST', 'GET'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')

    with open("user_infor.json", "r", encoding="utf-8") as f:
        json_data = json.load(f)
        if password == json_data[username]:
            session['username'] = username
            print(username, password)
            return render_template('index.html')
        else:
            return jsonify({"status": False, "data": "密码错误"})


@app.route('/set_key', methods=['POST'])
def set_key():
    # 从请求中获取数据
    data = request.json
    # database = data.get("database")
    key = data.get("key")
    value = data.get("value")
    qun = data.get("qun")
    values = [key, value, qun]
    print(values)

    # 切换到指定数据库
    # redis_client.connection_pool.connection_kwargs['db'] = int(database)

    # 设置键值对
    try:
        redis_client.rpush("infor_" + str(key), *values)
        redis_client.expire("infor_" + str(key), 1000)
        return jsonify({"status": "success", "message": "Key set successfully"}), 200
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


@app.route('/images/<filename>')
def serve_image(filename):
    return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True)


@app.route('/upload', methods=['GET', 'POST'])
def upload_image():
    if not request.files:
        return jsonify({'error': 'No file provided'}), 400


    print("已接受到数据")
    file = request.files['image']
    # file = request.files['video']
    # if not file:
    #     file = request.files['video']
    # print(file)
    # print(file.mimetype)

    # 验证文件类型
    if file.mimetype not in ['image/png', 'image/jpg', 'image/jpeg', 'image/gif', 'video/mp4', 'video/mov']:
        return jsonify({'error': 'Invalid file type. Only PNG and JPEG are supported.'}), 400

    # 生成唯一文件名
    file_extension = file.filename.split('.')[-1]  # 获取文件扩展名
    print(file_extension)
    unique_filename = f"{uuid.uuid4()}.{file_extension}"
    file_path = os.path.join(UPLOAD_FOLDER, unique_filename)

    # 保存图片到服务器文件系统
    try:
        file.save(file_path)
    except Exception as e:
        return jsonify({'error': f"Failed to save file: {str(e)}"}), 500

    # TODO: 将文件路径存入数据库
    # 示例：db.insert({'image_path': file_path})

    return jsonify({
        'message': 'uploaded successfully',
        'file_path': unique_filename  # 返回文件路径供前端使用
    }), 200


@app.route('/logout')
def logout():
    session.pop('username', None)


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=9001)
    # app.run(host='0.0.0.0', port=5000)
